package com.wc.alorithm_luogu.P1143;

import java.util.HashMap;
import java.util.Scanner;

/**
 * @Author congge
 * @Date 2023/10/8 22:22
 * @description 进制转换
 * https://www.luogu.com.cn/problem/P1143
 */
public class Main {
    static HashMap<Character, Integer> map = new HashMap<>();
    static char[] array = new char[16];

    public static void main(String[] args) {
        int idx = 0;
        for (char c = '0'; c <= '9'; c++) {
            array[idx] = c;
            map.put(c, idx++);
        }
        for (char c = 'A'; c <= 'F'; c++) {
            array[idx] = c;
            map.put(c, idx++);
        }

        Scanner sc = new Scanner(System.in);
        int preRadix = Integer.parseInt(sc.nextLine());
        String numStr = sc.nextLine();
        int curRadix = Integer.parseInt(sc.nextLine());
        Main main = new Main();
        int num = main.str2int(numStr, preRadix);
//        System.out.println(num);
        System.out.println(main.int2str(num, curRadix));
    }

    /**
     * 字符转换为10进制
     *
     * @param numStr 待转换的字符串
     * @param preRadix 进制数
     * @return
     */
    public int str2int(String numStr, int preRadix) {
        if (preRadix == 10) {
            return Integer.parseInt(numStr);
        }
        int ans = 0;
        int size = numStr.length();
        int maxFloor = (int) Math.pow(preRadix, size - 1);
        for (char c : numStr.toCharArray()) {
            ans += map.get(c) * maxFloor;
            maxFloor /= preRadix;
        }
        return ans;
    }

    /**
     * 10进制转换为对应进制数
     *
     * @param num 待转换为的进制数
     * @param curRadix 进制数
     * @return
     */
    public String int2str(int num, int curRadix) {
        if (curRadix == 10) {
            return String.valueOf(num);
        }
        if (num == 0) {
            return "0";
        }
        StringBuilder ans = new StringBuilder();
        while (num != 0) {
            int remainder = num % curRadix;
            ans.insert(0, array[remainder]);
            num /= curRadix;
        }

        return ans.toString();
    }
}
